#include <stdio.h>
#include <string.h>

#include "thread.h"
#include "ipc.h"

//#define USING_STATIC

#ifdef USING_STATIC
static mt_mq_t mq;
static mt_uint8_t pool[1024];
#endif
static mt_mq_t *pmq;

static void *thread1_func(void *arg)
{
    char *p = arg;
    char buffer[32];
    mt_size_t size;
    
    printf("%s\r\n", p);
    while(1)
    {
        size = sizeof(buffer);
        memset(buffer, 0, size);
        if(mt_mq_recv(pmq, buffer, &size,  MT_WAITING_FOREVER) == MT_EOK)
        {
            printf("size = %d\r\n", size);
            printf("msg = %s\r\n", buffer);
        }
        else
            printf("take message queue failed\r\n");
    }
}

static void *thread2_func(void *arg)
{
    char *p = arg;
    
    printf("%s\r\n", p);
    while(1)
    {
        if(mt_mq_send(pmq, "message 1", strlen("message 1")) != MT_EOK)
            printf("send message queue failed\r\n");
        if(mt_mq_send(pmq, "message queue 2", strlen("message queue 2")) != MT_EOK)
            printf("send message queue failed\r\n");
        if(mt_mq_urgent(pmq, "message queue test 3", strlen("message queue test 3")) != MT_EOK)
            printf("send message queue failed\r\n");
        mt_delay(1000);
    }
}

int mq_test(void)
{
    mt_thread_t *thread1_handle;
    mt_thread_t *thread2_handle;
    
#ifdef USING_STATIC
    mt_mq_init(&mq, "test_mq", pool, sizeof(pool), 32, MT_IPC_FLAG_FIFO);
    pmq = &mq;
#else
    pmq = mt_mq_create("test_mq", 5, 32, MT_IPC_FLAG_FIFO);
    if(pmq == MT_NULL)
    {
        printf("create message queue faied\r\n");
        return -1;
    }
#endif
    
    thread1_handle = mt_thread_create("thread1", 
                                      thread1_func, 
                                      "thread1", 
                                      1024, 
                                      12, 
                                      5);
    thread2_handle = mt_thread_create("thread2", 
                                      thread2_func, 
                                      "thread2", 
                                      1024, 
                                      11, 
                                      5);
    
    if((thread1_handle == MT_NULL) || (thread2_handle == MT_NULL))
    {
        printf("create thrtead faied\r\n");
        return -1;
    }
    mt_thread_start(thread1_handle);
    mt_thread_start(thread2_handle);
    
    return 0;
}
